function isEmpty(value) {
	return value == null || (typeof value == 'undefined');
}

function getAttribute(attr, value) {
	if (!isEmpty(value)) {
		return ' ' + attr + '="' + value + '" ';
	}
	
	return '';
}

function rssReaderShowHide(idContainer, id) {
	
	comp = this.container.component;
	
	var data = this.data[comp.selectedIndex]
	
	if (!data.readed) {
		comp.readed++;
		document.getElementById('rss_info').innerHTML = comp.readed + '/' + this.data.length;
	}
	
	data.readed = true;
			
	this.config.go(data);
		
	return false
}

function rssReaderSetSelected(idContainer, idRow) {
	var container = document.getElementById(idContainer);
	var component = container.component;
	
	if (component.selectedIndex != -1) {
		var rowx = document.getElementById('row_' + component.selectedIndex);
	
		if (rowx != null) {
			if (!this.data[component.selectedIndex].readed) {
				rowx.setAttribute('style', this.config.titleStyle);
				rowx.setAttribute('class', this.config.titleClass);
			} else {
				rowx.setAttribute('style', this.config.readedTitleStyle);
				rowx.setAttribute('class', this.config.readedTitleClass);
			}
		}	
	}
	
	var rowIndex = parseInt(idRow.split('_')[1]);
	
	var row = document.getElementById(idRow);
	
	row.setAttribute('style', this.config.selectedStyle);
	row.setAttribute('class', this.config.selectedClass);
	
	component.selectedIndex = rowIndex;
	
	return false;
}

var config;
var data;
var container;
function createRssReader(config, data, action) {
	this.config = config;
	this.data = data;
	
	var headerIcon = '';
	var imgHeader = '';
	
	if (action == 'previous') {
		if (config.currentPage > 0) { 
			config.currentPage--;
		} 
	} else if (action == 'next') {
		if ((data.length - ((config.currentPage + 1) * config.pageSize)) > 0) {
			config.currentPage++;
		} 
	} 
	
	var btnNextNews = document.getElementById("nextNews");
	if ((config.currentPage + 1) * config.pageSize > data.length) {
		btnNextNews.style.visibility = "hidden";
	} else {
		btnNextNews.style.visibility = "visible";
	}

	var btnPreviousNews = document.getElementById("previousNews");
	if ((config.currentPage * config.pageSize < config.pageSize)) {
		btnPreviousNews.style.visibility = "hidden";
	} else {
		btnPreviousNews.style.visibility = "visible";
	}
	
	if (!isEmpty(config.headerIcon)) {
		imgHeader = '<img border="0" src="' + config.headerIcon + '" />';
	}
	
	var id = config.renderTo;
	var headerId = id + 'Header';

	var divHeader = '<div id="' + headerId + '"';
	
	if (!isEmpty(config.headerStyle))
	 	divHeader += ' style="' + config.headerStyle + '"';
	
	if (!isEmpty(config.headerClass))
		divHeader += ' class="' + config.headerClass + '"';
		
	divHeader += '><table border=0 cellpading=0 cellspacing=0 ><tr>'; // width="100%" height="100%"
	
	if (imgHeader != '')
		divHeader += '<td>' + imgHeader + '</td>';
		
	divHeader += '<td valign="middle" align="center" width="100%" style="font-size:12px;">' + config.headerText + '</td><td style="padding-right: 3px; font-size:12px;" id="rss_info">$rss_info$</td></tr></table></div>';

	divContent = '<div style="overflow: hidden"';
	
	divContent += getAttribute('style', config.contentStyle);
	divContent += getAttribute('class', config.contentClass);
	
	divContent += '>';

	var firstRow;
	
	var readedCount = 0;
	
	var startIndex = (config.currentPage * config.pageSize);
	var endIndex = (startIndex + config.pageSize);

	for (var j = 0; j < data.length; j++) {
		if (data[j].readed) {	
			readedCount++;
		}	
	}
	
	container = document.getElementById(config.renderTo);
	container.component = container.component || {}; 
	container.config = config;
	container.data = data;
	container.component.readed = readedCount;
	
	container.component.selectedIndex = (config.currentPage * config.pageSize);
	
	for (var i = startIndex; i < endIndex && i < data.length; i++) {
		if (i > 0) {
			divContent += '<div style="background-color: transparent; height: 1px;">&nbsp;</div>';
		}
		
		var rowId = 'row_' + i;
		
		if (!isEmpty(firstRow))
			firstRow = rowId;
		
		divContent += '<div ' + getAttribute('id', rowId);
		
		if (i == container.component.selectedIndex) {
			divContent += getAttribute('style', config.selectedStyle) + ' ' + 
						  getAttribute('class', config.selectedClass) + '>';
		} else if (data[i].readed) {
			divContent += getAttribute('style', config.readedTitleStyle) + ' ' + 
						  getAttribute('class', config.readedTitleClass) + '>';
		} else {
			divContent += getAttribute('style', config.titleStyle) + ' ' + 
						  getAttribute('class', config.titleClass) + '>';
		}
		
		divContent += '<table border=0 cellpading=0 cellspacing=0><tr>';
		
		if (!isEmpty(data[i].icon)) {
			if (data[i].icon == "") {
				divContent += '<td style="padding: 1px;"></td>';	
			} else {
				divContent += '<td style="padding: 1px;"><img ' + getAttribute('src', data[i].icon) + ' border=1 /></td>';
			}
		}
		
		divContent += '<td valign="middle" align="left" width="100%">';
		
		divContent +=
			'<a ' + 
				getAttribute('id', 'link_' + i) +
				//getAttribute('onkeydown', 'return rssReaderShowHide(\'preview\',\'' + id + '\', \'' + rowId + '\')') +
				getAttribute('onclick', 'return false;') +
				getAttribute('href', 'javascript: return false;') +
				getAttribute('onfocus', 'return rssReaderSetSelected(\'' + id + '\', \'' + rowId + '\')') + 
				'><em>' + 
					data[i].title + 
			'</em></a></td></td></table></div>';
			
		divContent += '<div ' + 
			getAttribute('id', 'description_' + rowId) + 
			getAttribute('style', 'display: none;') + '>' +
			'<div' +
				getAttribute('style', config.descriptionStyle) +
				getAttribute('class', config.descriptionClass) + 
			'>';
			
		var description = data[i].description;
		
		if (description.length > config.descriptionMaxLength) {
			var length = config.descriptionMaxLength - 5;
			if (length < 0)
				length = config.descriptionMaxLength;
		
			description = description.slice(0, length);
			description += '...';
		}	
		divContent += description + '</div></div>';
	}
	
	divContent +='</div>';
	
	divHeader = divHeader.replace("$rss_info$", readedCount + '/' + data.length);
	
	container.innerHTML = divHeader + divContent +
		'<input type="button" style="visibility: hidden; position: absolute; top: -100px; left: -100px;" />';
	
	var link = document.getElementById('link_0');
	
	if (link) {
		link.focus();
		container.component.selectedIndex = 0;
	}
	
	return container;
}

function toString(obj) {
	var str = '';
	
	if (typeof obj == 'string') {
		str = '"' + escape(obj) + '"';
		
	} else if (typeof obj == 'number') {
		str = obj;
		
	} else if (typeof obj == 'object' && obj.length) {
		
		var array = [];
		var i = 0;
		
		for (var j = 0; j < obj.length; j++) {
			array[i] = toString(obj[j]);
		
			i++;
		}
		
		str = '['+ array.join(',') + ']';
	} else {
		var array = [];
		var i = 0;
		
		for (var prop in obj) {
			var subProp = obj[prop];
			
			array[i] = prop + ':' + toString(subProp);
			
			i++;	
		}
		
		str = '{' + array.join(',') + '}';
	}
	
	return str;
}

function backNews() {
	showNews();
}

function changeRssPage(action) {
	createRssReader(this.config, this.data, action);
}

function toObject(string) {
	return eval('(' + unescape(string) + ')');
}

function parseNews (xmlNode, args) {
	if (xmlNode == "networkError" || xmlNode == "timeout") {
		showError(xmlNode, "parseNews(xmlNode, args)");
		return;
	}
	var reader = new RSSReader();
	widgetNews = reader.parse(xmlNode);
	var news = [];
	
	for (var i = 0; i < widgetNews.length; i++){	
		
		var value = widget.preferenceForKey(widgetNews[i].getTitle().substring(0,17));
		if(value != undefined && value != "") {
			var buffer = document.getElementById('bufferDiv');
			buffer.innerHTML = widgetNews[i].getText();
			
			news.push({  title: widgetNews[i].getTitle(),
				description: getText(buffer),
				icon: '',
				readed: true});
		}else{
			var buffer = document.getElementById('bufferDiv');
			buffer.innerHTML = widgetNews[i].getText();
			
			news.push({  title: widgetNews[i].getTitle(),
				description: getText(buffer),
				icon: ''});
		}
	}
	createRssReader({
			renderTo: NEWSCONTENTS,
			headerText: getSelectedCountry(),
			// headerIcon: './img/rssIcon.png',
			headerClass: 'newsReaderHeader',
			headerStyle: 'height: 19px;',
			selectedClass: 'newsItemBGSelected',
			// selectedStyle: 'background-color: orange;',
			contentClass: 'newsClass',
			// titleStyle: 'font-color: red;',
			titleClass: 'newsItemBG',
			readedTitleStyle: 'font-color: #333333;',
			readedTitleClass: 'newsItemBGReaded',
			descriptionStyle: 'height: 20px; margin-top:-10px; margin-left:3px;',
			descriptionClass: 'newsItemBGVisualization',
			descriptionMaxLength: 90,
			currentPage: 0,
			pageSize: 4,
			go: function(noticia) {
				widget.setPreferenceForKey("true",noticia.title.substring(0,17));

				showNewItem(noticia.description, noticia.title);
			}
		},
		news
	);
	showNews();
}

function showNewItem(description, title){
	readDivContents.innerHTML = '<div id="newsItem-view" class="newsItemClass" >'+
		'<table border=0><tr><th>' + title +'</th>' +
		'<tr><td><p style="padding-left: 3px; margin-top: 0px;"><br/>'+ description + '</p></td></tr></table>' + 
		'</div>';
	readDiv.style.display = "block";
	newsDiv.style.display = "none";
}

function getText(comp) {
	if (comp.nodeName == 'A') {
		return '';
	}

	if (comp.nodeName == '#text') {
		return comp.nodeValue;
	}

	var str = '';

	for (var i = 0; i < comp.childNodes.length; i++) {
		str += getText(comp.childNodes[i]);
	}

	return str;
}